package com.hooview.web.controller;

import com.hooview.api.entity.News;
import com.hooview.api.service.JPushService;
import com.hooview.api.service.NewsService;
import com.hooview.utils.AjaxMsg;
import com.hooview.utils.AssertUtils;
import com.hooview.utils.Paginator;
import com.hooview.utils.QueryFilters;
import com.hooview.utils.QueryRule;
import com.hooview.utils.SqlConditionWrapper;
import com.hooview.utils.ValidUtil;
import com.hooview.web.template.ExecuteCallBack;
import com.hooview.web.template.ExecuteTemplate;
import com.hooview.web.vo.NewsVO;
import me.gavincook.sso.client.annotation.LoginRequired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 资讯控制器
 *
 * @author gavincook
 * @version $ID: NewsController.java, v0.1 2018-05-25 11:58 gavincook Exp $$
 */
@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private ExecuteTemplate executeTemplate;

    @Autowired
    private NewsService newsService;

    @Autowired
    private JPushService jPushService;

    /**
     * 资讯查询，通过channelId来区分是何种类型的资讯
     *
     * @param channelId 渠道ID，1：快讯，2：微博，3，头条
     *                  改动： 1：关注，2：头条，3：对话，4：走势，5：前沿，6：学院 ，7：快讯
     * @param pageSize  每页条数
     * @param pageNum   页码
     * @param title     关键字，搜索标题
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    @LoginRequired
    public AjaxMsg search(String channelId, Integer pageSize, Integer pageNum, String title, String createTime,
                          Integer candy, Integer expireTime, String author, String tag, String status) {

        QueryFilters filters = new QueryFilters();

        AjaxMsg ajaxMsg = new AjaxMsg();
        executeTemplate.executeWithoutTransaction(new ExecuteCallBack() {
            @Override
            public void check() {
                filters.setPageNo(pageNum);
                filters.setPageSize(pageSize);
                if (!ValidUtil.isEmpty(channelId)) {
                    QueryRule queryRule = new QueryRule();
                    queryRule.setField("channel_id");
                    queryRule.setOp("eq");
                    queryRule.setData(channelId);
                    filters.getRules().add(queryRule);
                }

                if (!ValidUtil.isEmpty(expireTime)) {
                    QueryRule queryRule = new QueryRule();
                    queryRule.setField("expire_time");
                    queryRule.setOp("eq");
                    queryRule.setData(Integer.toString(expireTime * 60));
                    filters.getRules().add(queryRule);
                }


                if (!ValidUtil.isEmpty(title)) {
                    QueryRule queryRule = new QueryRule();
                    queryRule.setField("title");
                    queryRule.setOp("like");
                    queryRule.setData(SqlConditionWrapper.wildcard(title));
                    filters.getRules().add(queryRule);
                }


                if (!ValidUtil.isEmpty(tag)) {
                    QueryRule queryRule = new QueryRule();
                    queryRule.setField("tag");
                    queryRule.setOp("like");
                    queryRule.setData(SqlConditionWrapper.wildcard(tag));
                    filters.getRules().add(queryRule);
                }

                if (!ValidUtil.isEmpty(author)) {
                    QueryRule queryRule = new QueryRule();
                    queryRule.setField("author");
                    queryRule.setOp("like");
                    queryRule.setData(SqlConditionWrapper.wildcard(author));
                    filters.getRules().add(queryRule);
                }

                if (!ValidUtil.isEmpty(candy)) {
                    QueryRule queryRule = new QueryRule();
                    queryRule.setField("candy");
                    queryRule.setOp("eq");
                    queryRule.setData(candy.toString());
                    filters.getRules().add(queryRule);
                }

                if (!ValidUtil.isEmpty(status)) {
                    QueryRule queryRule = new QueryRule();
                    queryRule.setField("n.status");
                    queryRule.setOp("eq");
                    queryRule.setData(status.toString());
                    filters.getRules().add(queryRule);
                }

                if (!ValidUtil.isEmpty(createTime)) {
                    String[] createTimeRange = createTime.split("\\s-\\s");
                    if (createTimeRange.length != 2) {
                        throw new IllegalArgumentException("创建时间参数非法");
                    }
                    QueryRule startRule = new QueryRule();
                    startRule.setField("create_time");
                    startRule.setOp("ge");
                    startRule.setData(createTimeRange[0].trim());
                    filters.getRules().add(startRule);

                    QueryRule endRule = new QueryRule();
                    endRule.setField("create_time");
                    endRule.setOp("le");
                    endRule.setData(createTimeRange[1].trim());
                    filters.getRules().add(endRule);
                }

                filters.setSidx("create_time");
                filters.setSord("DESC");
            }

            @Override
            public void service() {

                //总数
                Integer count = newsService.getCountByFilter(filters);

                //如果计数器为0，则表示没有数据
                if (count == 0) {
                    ajaxMsg.setDatas(Paginator.ofEmpty(pageSize));
                    return;

                }

                //分页数据
                List<Map<String,Object>> list = newsService.getMapByFilter(filters);

                //构建分页对象
                Paginator<Map<String,Object>> paginator = new Paginator<>(count, list, pageNum, pageSize);
                ajaxMsg.setDatas(paginator);

            }
        }, ajaxMsg);


        return ajaxMsg;
    }

    /**
     * 新增资讯
     *
     * @param news 资讯实体
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public AjaxMsg createNews(@RequestBody NewsVO news) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        executeTemplate.executeWithoutTransaction(new ExecuteCallBack() {
            @Override
            public void check() {
                AssertUtils.assertNotNull(news);
                AssertUtils.assertNotNull(news.getChannelId(), "渠道标识不能为空");
            }

            @Override
            public void service() {
                news.setCreateTime(new Date());
                //将前端的过期时间戳转换为过期分钟数
                if (news.getExpireTimeStamp() != null) {
                    news.setExpireTime((int) ((news.getExpireTimeStamp() - System.currentTimeMillis()) / 1000 / 60));
                }
                Integer id = newsService.insert(news);
                jPushService.pushNews(id);
                ajaxMsg.setDatas(true);
            }
        }, ajaxMsg);


        return ajaxMsg;
    }

    /**
     * 获取资讯详情
     *
     * @param id 资讯id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public AjaxMsg getNews(@PathVariable("id") Integer id) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        executeTemplate.executeWithoutTransaction(new ExecuteCallBack() {
            @Override
            public void check() {
                AssertUtils.assertPositiveIntegerNumber(id);
            }

            @Override
            public void service() {
                ajaxMsg.setDatas(newsService.selectByPrimaryKey(id));
            }
        }, ajaxMsg);


        return ajaxMsg;
    }

    /**
     * 更新资讯
     *
     * @param news 资讯实体
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.PUT)
    @ResponseBody
    @LoginRequired
    public AjaxMsg updateNews(@RequestBody NewsVO news) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        executeTemplate.executeWithoutTransaction(new ExecuteCallBack() {
            @Override
            public void check() {
                AssertUtils.assertNotNull(news);
                AssertUtils.assertPositiveIntegerNumber(news.getId());
            }

            @Override
            public void service() {
                //将前端的过期时间戳转换为过期分钟数
                if (news.getExpireTimeStamp() != null) {
                    news.setExpireTime((int) ((news.getExpireTimeStamp() - System.currentTimeMillis()) / 1000 / 60));
                }
                ajaxMsg.setDatas(newsService.updateByPrimaryKeySelective(news) > 0);
            }
        }, ajaxMsg);


        return ajaxMsg;
    }


    /**
     * 删除资讯
     *
     * @param news 资讯实体
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.DELETE)
    @ResponseBody
    @LoginRequired
    public AjaxMsg deleteNews(@RequestBody News news) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        executeTemplate.executeWithoutTransaction(new ExecuteCallBack() {
            @Override
            public void check() {
                AssertUtils.assertNotNull(news);
                AssertUtils.assertPositiveIntegerNumber(news.getId());
            }

            @Override
            public void service() {
                ajaxMsg.setDatas(newsService.deleteByPrimaryKey(news.getId()) > 0);
            }
        }, ajaxMsg);


        return ajaxMsg;
    }
}
